/**
 * @file UserProfilePage.jsx
 * @description 用户个人中心页面组件 (受保护)。
 */
import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import { logout, updateUserProfile } from '../store/authSlice';
import { clearOrders } from '../store/orderSlice'; // 导入 clearOrders
import { clearWishlist } from '../store/wishlistSlice'; // 导入 clearWishlist
import toast from 'react-hot-toast';
import { FaUserEdit, FaBoxOpen, FaSignOutAlt, FaEnvelope, FaUserCircle, FaHeart, FaMapMarkerAlt } from 'react-icons/fa';

const UserProfilePage = () => {
  const { user } = useSelector((state) => state.auth);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [showEditModal, setShowEditModal] = useState(false);
  const [editForm, setEditForm] = useState({ name: '', email: '' });
  const [validated, setValidated] = useState(false);

  useEffect(() => {
    if (user) {
      setEditForm({ name: user.name, email: user.email });
    }
  }, [user, showEditModal]);

  const handleLogout = () => {
    dispatch(logout());
    dispatch(clearOrders()); 
    dispatch(clearWishlist()); // 在登出时清除心愿单
    toast.success('您已成功退出登录！');
    navigate('/login');
  };

  const handleShowEditModal = () => {
    setValidated(false);
    setShowEditModal(true);
  };
  const handleCloseEditModal = () => setShowEditModal(false);

  const handleEditFormChange = (e) => {
    const { name, value } = e.target;
    setEditForm(prev => ({ ...prev, [name]: value }));
  };

  const handleEditSubmit = (event) => {
    event.preventDefault();
    const form = event.currentTarget;
    if (form.checkValidity() === false) {
      event.stopPropagation();
      toast.error('请检查输入内容。');
      setValidated(true);
      return;
    }
    setValidated(true);

    dispatch(updateUserProfile({ name: editForm.name, email: editForm.email }));
    toast.success('个人资料已更新！');
    handleCloseEditModal();
  };

  if (!user) {
    return (
      <div className="container my-5 py-5 text-center">
        <p>请先登录以查看用户中心。</p>
      </div>
    );
  }

  return (
    <>
      <div className="container my-5 py-5">
        <div className="row mb-4">
          <div className="col-12 text-center">
            <h1 className="display-5 fw-bold">我的账户</h1>
            <hr />
          </div>
        </div>

        <div className="row justify-content-center">
          <div className="col-md-10 col-lg-8">
            <div className="card shadow-sm mb-4">
              <div className="card-header bg-dark text-white d-flex align-items-center">
                <FaUserCircle className="me-2 fs-4" />
                欢迎回来, {user.name}!
              </div>
              <div className="card-body">
                <p className="card-text">
                  <FaEnvelope className="me-2 text-muted" />
                  <strong>邮箱:</strong> {user.email}
                </p>
                <p className="card-text">
                  <strong>用户 ID (模拟):</strong> {user.id}
                </p>
                <button className="btn btn-outline-primary btn-sm mt-2" onClick={handleShowEditModal}>
                  <FaUserEdit className="me-1" />
                  编辑个人资料
                </button>
              </div>
            </div>

            <div className="row">
              <div className="col-md-6 mb-3">
                <div className="card h-100 shadow-sm">
                  <div className="card-body text-center d-flex flex-column justify-content-center align-items-center">
                    <FaBoxOpen size={40} className="mb-3 text-primary" />
                    <h5 className="card-title">我的订单</h5>
                    <p className="card-text text-muted small">查看您的订单历史和状态。</p>
                    <Link to="/orders" className="btn btn-primary mt-auto">查看订单</Link>
                  </div>
                </div>
              </div>
              <div className="col-md-6 mb-3">
                <div className="card h-100 shadow-sm">
                  <div className="card-body text-center d-flex flex-column justify-content-center align-items-center">
                    <FaHeart size={40} className="mb-3 text-danger" />
                    <h5 className="card-title">我的心愿单</h5>
                    <p className="card-text text-muted small">管理您收藏的商品。</p>
                    {/* 修改按钮为 Link */}
                    <Link to="/wishlist" className="btn btn-outline-danger mt-auto">查看心愿单</Link>
                  </div>
                </div>
              </div>
            </div>

            <div className="text-center mt-4">
              <button onClick={handleLogout} className="btn btn-danger">
                <FaSignOutAlt className="me-1" />
                退出登录
              </button>
            </div>
          </div>
        </div>
      </div>

      {showEditModal && (
        <div className="modal fade show" tabIndex="-1" style={{ display: 'block' }} aria-labelledby="editProfileModalLabel" aria-modal="true" role="dialog">
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content">
              <div className="modal-header">
                <h5 className="modal-title" id="editProfileModalLabel">编辑个人资料</h5>
                <button type="button" className="btn-close" onClick={handleCloseEditModal} aria-label="Close"></button>
              </div>
              <form className={`needs-validation p-3 ${validated ? 'was-validated' : ''}`} noValidate onSubmit={handleEditSubmit}>
                <div className="modal-body">
                  <div className="mb-3">
                    <label htmlFor="editName" className="form-label">姓名</label>
                    <input
                      type="text"
                      className="form-control"
                      id="editName"
                      name="name"
                      value={editForm.name}
                      onChange={handleEditFormChange}
                      required
                    />
                    <div className="invalid-feedback">请输入您的姓名。</div>
                  </div>
                  <div className="mb-3">
                    <label htmlFor="editEmail" className="form-label">邮箱</label>
                    <input
                      type="email"
                      className="form-control"
                      id="editEmail"
                      name="email"
                      value={editForm.email}
                      onChange={handleEditFormChange}
                      required
                    />
                    <div className="invalid-feedback">请输入有效的邮箱地址。</div>
                  </div>
                </div>
                <div className="modal-footer">
                  <button type="button" className="btn btn-secondary" onClick={handleCloseEditModal}>取消</button>
                  <button type="submit" className="btn btn-primary">保存更改</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
      {showEditModal && <div className="modal-backdrop fade show"></div>}
    </>
  );
};

export default UserProfilePage;